/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package cn.yunyichina.provider.pay.alipay.executor;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.base.PlatformExtensionUserVo;
import cn.yunyichina.provider.iface.entity.base.PlatformExtensionVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.pay.alipay.entity.PublicFollowExecutorActionParam;
import cn.yunyichina.provider.pay.alipay.utils.AlipayMsgBuildUtil;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 关注服务窗执行器
 *
 */
public class InAlipayFollowExecutor implements ActionExecutor {

    private static final Logger logger = LoggerFactory.getLogger(InAlipayFollowExecutor.class);

    /** 业务参数 */
    private Map<String, String> bizContent;

    private PaymentSettingResponse paymentSetting;

    public InAlipayFollowExecutor(Map<String, String> bizContent , PaymentSettingResponse paymentSetting) {
        this.bizContent = bizContent;
        this.paymentSetting = paymentSetting;
    }

    public InAlipayFollowExecutor() {
        super();
    }

    @Override
    public String execute() {
        final String fromUserId = bizContent.get("FromUserId");

        //业务：保存扫码关注信息
        saveScaner(bizContent);

        // 直接构造简单响应结果返回
        return AlipayMsgBuildUtil.buildBaseAckMsg(fromUserId , paymentSetting.getPayAppId());
    }


    /**
     * 保存扫码关注信息
     * @param bizContent
     */
    public String saveScaner(Map<String, String> bizContent){
        logger.info("InAlipayFollowExecutor.saveScaner  bizContentJson -> {}", JsonUtils.toJsonString(bizContent));
        String openId = bizContent.get("FromAlipayUserId");
        String actionParam = bizContent.get("ActionParam");  //回调参数

        logger.info("InAlipayFollowExecutor.saveScaner  actionParam：" +  actionParam);

        Response response = new Response();

        //从回调参数actionParam中获得推广人信息
        JSONObject dataJson = JSON.parseObject(actionParam);
        Object scene = dataJson.get("scene");

        PublicFollowExecutorActionParam publicFollowExecutorActionParam = JSONObject.parseObject(scene.toString(), PublicFollowExecutorActionParam.class);

        logger.info("InAlipayFollowExecutor.saveScaner actionParam参数中获取到推广人员id：" + publicFollowExecutorActionParam.getSceneId());

        if(publicFollowExecutorActionParam != null && StringUtils.isNotBlank(publicFollowExecutorActionParam.getSceneId())){

            Map<String,String > map =new HashMap<String ,String >();
            map.put("id" , publicFollowExecutorActionParam.getSceneId());

            //查询推广人信息
            response = BaseService.callHumpFromInternal("yyt.base.scaner.platform.info.select", JsonUtils.toJsonString(map));
            if("0".equals(response.getResultCode())){
                List<PlatformExtensionVo> extensionVos = JsonUtils.parseArray(response.getResult(), PlatformExtensionVo.class);
                PlatformExtensionVo extensionVo = extensionVos.get(0);
                PlatformExtensionUserVo extensionUserVo = new PlatformExtensionUserVo();
                extensionUserVo.setId(PKGenerator.generateId());
                extensionUserVo.setPersonalOpenId(openId);
                extensionUserVo.setOrgUserOpenId(extensionVo.getOrgUserOpenId());
                extensionUserVo.setOrgUserId(extensionVo.getOrgUserId());
                extensionUserVo.setOrgUserName(extensionVo.getOrgUserName());
                extensionUserVo.setPlatformExtensionId(extensionVo.getId());
                extensionUserVo.setCreatedTime(DateUtils.getDateTimeStr());
                extensionUserVo.setUpdateTime(DateUtils.getDateTimeStr());
                response = BaseService.callHumpFromInternal("yyt.base.scaner.platform.user.add", JsonUtils.toJsonString(extensionUserVo));
                if("0".equals(response.getResultCode())){
                    logger.info("保存扫码关注信息成功 extensionUserVo：" + JsonUtils.toJsonString(extensionUserVo));
                }
            }else{
                logger.info("根据id查询推广人信息失败  id:" + publicFollowExecutorActionParam.getSceneId());
            }
        }

        return  response.getResultMessage();
    }


    public static void main(String[] args) {
        String actionParam = "{\"scene\":{\"sceneId\":\"a008afe5ff044845a7fd46b58126c6bc\"}}";
        JSONObject dataJson = JSON.parseObject(actionParam);
        Object scene = dataJson.get("scene");
        System.out.println(scene.toString());
        PublicFollowExecutorActionParam publicFollowExecutorActionParam = JSONObject.parseObject(scene.toString(), PublicFollowExecutorActionParam.class);
        System.out.println(publicFollowExecutorActionParam.getSceneId());
    }
}
